<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Issue;

use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\System\AuctionException;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Account\Back\Employee;




/**
 * 车主争议模型
 * @author   Administrator
 */
class OwnerIssue
{
    const STATUS_PENDING = 0; // 待处理
    const STATUS_SUCCESS = 1; // 协商成功
    const STATUS_FAILD = 2; // 协商失败

    public static $dataStatus = array(
            'pending' => self::STATUS_PENDING,
            'success' => self::STATUS_SUCCESS,
            'faild' => self::STATUS_FAILD,
    );

    protected $order_id = null;

    /**
     * 构造
     * @param    int $order_id 拍单编号 或 拍单id
     * @return   void
     */
    public function __construct($order_no_or_id='')
    {
        $this->order_id = $order_no_or_id;
    }

    /**
     * 车主争议详情。
     * @return   Array
     */
    public static function detail_by_issue_id($issue_id)
    {
        $cond = array(
            'issue_id' => $issue_id
        );
        $res =  M('owner_issue')->where($cond)->find();
        return $res;
    }

    private function checkOrderID() {
        if (!is_numeric($this->order_id)) {
            $r = M('order')->field('order_id')->where("order_no='{$this->order_id}'")->find();
            if ($r && count($r) > 0) {
                $this->order_id = $r['order_id'];
            } else {
                AuctionException::make_throw('700002');
            }
        }
    }

    /**
     * 按照order_id获取车主争议记录
     * 
     * @param integer $orderID
     * @return mix
     */
    public static function getIssueInfoByOrderID($orderID) {
        if (!isset($orderID) || !is_numeric($orderID)) {
            AuctionException::make_throw('1700001');
        }
        $cols = 'oi.*';
        $map = array(
            'oi.order_id' => $orderID
        );
        $res = M('owner_issue')->alias('oi')->field($cols)->where($map)->find();
        return $res;
    }

    /**
     * 获取车主争议列表
     * @param integer $page
     * @param int $size
     * @param unknown $paramer
     * @return multitype:unknown string
     */
    public function issue_owner_list($page = 1, $size = 10, $params) {
        $page = (int) $page < 1 ? 1 : (int) $page;
        $size = (int) $size < 1 ? 10 : (int) $size;
        $order = "o.last_time desc";
        $map = array();
        if (isset($params['status']) && is_numeric($params['status'])) {
            // $map .= "di.status=" . $params['status'];
            $map[] = array('oi.status' => $params['status']);
        }
        if (!empty($params['location_area'])) {
            $map[] = array('c.location_area' => $params['location_area']);
        }
        if (isset($params['comeFrom']) && $params['comeFrom'] !== '' && $params['comeFrom'] != '-2') {            
            $map[] = array('co.comefrom' => $params['comeFrom']);
        }

        if (!empty($params['order_no'])) {
            $map[] = array('o.order_no' => $params['order_no']);
        }
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.last_time,
            c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,co.seller_name,co.phone,co.sign_reserve_time,
            c.vin,c.car_color,c.accident_level,c.transfer_limit,c.composite_state,c.history_state,
            co.sign_reserve_province,co.sign_reserve_store,co.sign_service_method,co.sign_date,
            co.sign_reserve_city,co.sign_reserve_area,co.sign_reserve_address,co.deliver_id,o.is_sign_tracing,co.comefrom,co.comefrom_url,
            oi.issue_id,
            em.real_name as checker_name,em.mobile as checker_mobile,
            rc.condition_checker,rc.procedure_checker,rc.next_trace_time,rc.recheck_time,rc.remark as recheck_remark,
            emrc.real_name as condition_checker_name";
        $prefix = C('DB_PREFIX');
        $total = M('order')->alias('o')
                        ->join($prefix . "cars as c ON c.car_id=o.car_id")
                        ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
                        // ->join($prefix . "dealer_auctioned as re ON re.order_id=o.order_id")
                        // ->join($prefix . "car_dealer as cd ON cd.dealer_id=re.dealer_id")
                        ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=co.checker_id")
                        ->join($prefix . "owner_issue as oi ON oi.order_id=o.order_id")
                        ->join('LEFT JOIN ' . $prefix . "recheck as rc ON rc.order_id=o.order_id")
                        ->join('LEFT JOIN ' . $prefix . "employee as emrc ON emrc.emp_id=rc.condition_checker")
                        ->where($map)->count();

        $list = M('order')->alias('o')->field($cols)
                        ->join($prefix . "cars as c ON c.car_id=o.car_id")
                        ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
                        // ->join($prefix . "dealer_auctioned as re ON re.order_id=o.order_id")
                        // ->join($prefix . "car_dealer as cd ON cd.dealer_id=re.dealer_id")
                        ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=co.checker_id")
                        ->join($prefix . "owner_issue as oi ON oi.order_id=o.order_id")
                        ->join('LEFT JOIN ' . $prefix . "recheck as rc ON rc.order_id=o.order_id")
                        ->join('LEFT JOIN ' . $prefix . "employee as emrc ON emrc.emp_id=rc.condition_checker")
                        ->where($map)->limit($size)->page($page)->order($order)->select();

        //echo M("order")->getLastSql();
        //数据处理
        if (!empty($list)) {
            $cm = new CarModel();
            $addr = new \AuctionCore\Other\Address();
            foreach ($list as $key => $val) {
                $list[$key] = $val;
                if ($list[$key]['is_sign_tracing'] == 0) {
                    $list[$key]['sign_reserve_time'] = transform_date($val['sign_reserve_time'], 1);
                }
                $list[$key]['location_area_name'] = $addr->get_name_by_code($val['location_area']);

                $list[$key]['car_plate_number'] = C('PLATE_PREFIX')[$val['plate_prefix']] . $val['plate_suffix'];
                $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $model = $cm->get_model_by_id($val['model_id']);
                if ($val['sign_service_method'] == 2) {
                    $province = $addr->get_name_by_code($val['sign_reserve_province']);
                    $city = $addr->get_name_by_code($val['sign_reserve_city']);
                    $area = $addr->get_name_by_code($val['sign_reserve_area']);
                    $list[$key]['address'] = $province . " " . $city . " " . $area . " " . $val['sign_reserve_address'];
                } elseif ($val['sign_service_method'] == 3) {
                    $list[$key]['address'] = C('STORE.' . $val['sign_reserve_store']);
                } else {
                    $list[$key]['address'] = "未知";
                }
                $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
                if ($params['auth']) {
                    $deliver = Employee::user_info_id($val['deliver_id']);
                    $list[$key]['deliver_name'] = $deliver['real_name'];
                }
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 获取车主争议数据详情
     *
     * 拍单、车源、车主信息、评估师信息、复检信息
     * 
     * @param int $issueStatus 车商争议数据状态(0:待处理, 1:协商成功 , 2:协商失败)
     *
     * @return fix
     **/
    public function issue_owner_detail()
    {
        $this->checkOrderID();
        //要查询的详情
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.bid_best_price,o.bidding_best_price,o.bidding_end_time,o.bidding_start_time,o.act_elapsed_time,o.first_pay_status,o.is_consult,o.company_subsidies,
            o.success_price,o.owner_confirm_service_id,o.fail_type,o.first_money,o.tail_money,o.is_self_confirm,o.last_time,
            c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,co.seller_name,co.phone,co.sign_reserve_time,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,
            c.vin,c.car_color,c.accident_level,c.transfer_limit,c.composite_state,c.history_state,c.car_source,
            co.sign_reserve_province,co.sign_reserve_store,co.sign_service_method,co.sign_date,co.check_date,co.owner_id,co.owner_type,co.contact_person,
            co.sign_reserve_city,co.sign_reserve_area,co.sign_reserve_address,co.deliver_id,o.is_sign_tracing,co.comefrom,co.comefrom_url,
            em.real_name as checker_name,em.mobile as checker_mobile,
            oi.issue_id,oi.status as issue_status,oi.updatetime as issue_done_time,oi.emp_id as issue_done_empid,oi.cut_down_price,oi.remark,
            emoi.real_name as issue_done_emp,
            rc.condition_checker,rc.procedure_checker,rc.next_trace_time,rc.recheck_time,rc.remark as recheck_remark,
            emrc.real_name as condition_checker_name";
        $prefix = C('DB_PREFIX');
        $cond = "o.order_id='" . $this->order_id . "'";
        $res = M('order')->alias('o')->field($cols)
                        ->join($prefix . "cars as c ON c.car_id=o.car_id")
                        ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
                        ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=co.checker_id")
                        ->join('LEFT JOIN ' . $prefix . "owner_issue as oi ON oi.order_id=o.order_id")
                        ->join('LEFT JOIN ' . $prefix . "employee as emoi ON emoi.emp_id=oi.emp_id")
                        ->join('LEFT JOIN ' . $prefix . "recheck as rc ON rc.order_id=o.order_id")
                        ->join('LEFT JOIN ' . $prefix . "employee as emrc ON emrc.emp_id=rc.condition_checker")
                        ->where($cond)->find();

// return M('order')->getLastSql();
        $cm = new \AuctionCore\CarResource\CarModel();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['format_reserve_price'] = format_money($res['reserve_price']);
        $res['format_best_price'] = format_money($res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price']);
        $res['best_price'] = $res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.'.$res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = round($res['pointer_mileage'] / 10000,2);
        $addr = new \AuctionCore\Other\Address();
        $res['location_area_name'] = $addr->get_name_by_code($res['location_area']);
        $res['reg_city'] = $addr->get_name_by_code($res['reg_city']);
        $res['car_plate_number'] = C('PLATE_PREFIX')[$res['plate_prefix']] . $res['plate_suffix'];
        $res['owner_type_name'] = C('OWNER_TYPE_NAME')[$res['owner_type']];
        return $res;
    }


    /**
     * 添加车商争议记录
     *
     * 更改争议处理状态，"协商补偿"=>"协商成功", "车商违约"=>"协商失败"
     * 协商补偿：如果是金牌车商，可以选择过户类型；当选择车商自过类型时需要记录提车人
     * 车商违约：违约扣款金额上限不得超过2000元
     * 记录备注信息
     *
     * @param    Array $data 需更新数据
     * @return   boolean
     */
    public function add_owner_issue($data=array())
    {
        //事务开始
        M()->startTrans();
        // 记录车商争议处理结果
        $params = array(
            'order_id' => $data['order_id'],
            'owner_id' => $data['owner_id'],
            'status' => 0,
            'createtime' => date('Y-m-d H:i:s')
        );
        $dealer_issue = M('owner_issue');
        $res_dealer_issue = $dealer_issue->add($params);
        if ($res_dealer_issue) {
            //事务提交
            M()->commit();
            //记录操作日志
            $log = array('order_id' => $data['order_id'], 'owner_id' => $data['owner_id'], 'action' => '产生车商争议');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            \Think\Log::record('添加车商争议时发生回滚事件！order_id:' . $data['order_id'] . ',owner_id:' . $data['owner_id']);
            return false;
        }
    }

    /**
     * 保存车主争议处理结果
     * 
     * 更改争议处理状态，"车主降价"=>"协商成功", "车主不卖"=>"协商失败"
     * 记录备注信息
     * 
     * @param    Array $data 需更新数据
     * @return   boolean
     */
    public function save_owner_issue($data=array())
    {
        // $this->checkOrderID();
        if (!isset($data['issue_id']) || !is_numeric($data['issue_id'])) {
            AuctionException::make_throw('1700001');
        }
        if (!isset($data['status']) || !is_numeric($data['status'])) {
            AuctionException::make_throw('1700002');   
        }

        $issueInfo = self::detail_by_issue_id($data['issue_id']);
        if (isset($issueInfo['status']) && $issueInfo['status'] != self::$dataStatus['pending']) {
            AuctionException::make_throw('22000001');
        }

        //事务开始
        M()->startTrans();
        // 记录车主争议处理结果
        $params = array(
                'emp_id' => $data['emp_id'],
                'status' => $data['status'],
                'cut_down_price' => $data['cut_down_price'],
                'remark' => $data['remark'],
                'updatetime' => date('Y-m-d H:i:s')
            );
        $owner_issue = M('owner_issue');
        $res_owner_issue = $owner_issue->where(array('issue_id'=>$data['issue_id']))->save($params);
        if (!$res_owner_issue) {
            M()->rollback();
            \Think\Log::record('处理车主争议时发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }
        
        
        $order_issue = new AuOrder($data['order_id']);

        if ($data['status'] == 1 ) { // 协商成功
            /*修改au_order表，标记车主争议协商成功*/
            $paramsIssue = array(
                    'return_check_status' => 7 ,
                    'depreciate' => is_numeric($data['cut_down_price']) ? $data['cut_down_price'] : 0,
            );
            $res_order = $order_issue->update($paramsIssue);
            if ($res_order === false) {
                M()->rollback();
                \Think\Log::record('处理车主争议时发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
                return false;
            }
            $actionCar = '车主争议，协商成功';
        } elseif ($data['status'] == 2) { // 车主不卖协商失败
            $paramsIssue = array(
                    'status' => 12 // 拍单状态(-1 删除,1审核中,2审核驳回,3投标中,301等待竞标,4竟标中,5待确认,7待签约,8待付首款，801已付首款,9待过户,10过户中,11待付尾款,12拍单失败,13拍单成功)
            );
            $res_order = $order_issue->update($paramsIssue);
            $cars_issue = new Car($data['car_id']);//M('cars');
            $paramsIssue = array(
                    'car_status' => 8  // 车辆状态(-1删除,1 待审核,2 审核失败,3 审核驳回,4 待拍卖,5 拍卖中,6 流拍,7 待重拍, 8 交易失败, 9 交易成功)
            );
            $res_cars = $cars_issue->update($paramsIssue);
            if ($res_order === false || $res_cars === false) {
                M()->rollback();
                \Think\Log::record('处理车主争议时发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
                return false;
            }
            try {
                AssetCenter::free_all($data['order_id']);
            } catch (AuctionException $ex) {
                M()->rollback();
                AuctionException::make_throw('500074'); //解冻保证金出错
            }
            $actionCar = '车主争议，车主不卖';
        }

        //事务提交
        M()->commit();
        //记录操作日志
        $log = array('order_id' => $data['order_id'], 'emp_id' => $data['emp_id'], 'action' => '处理车主争议');
        \AuctionCore\System\SystemLog::add($log);
        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $actionCar,
            'emp_id' => $data['emp_id']
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($data['car_id'], $car_action_data);
        /*记录拍品跟踪日志*/
        $order_action_data = array(
            'action_name' => $actionCar,
            'emp_id' => $data['emp_id']
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($data['order_id'], $order_action_data);
        return true;
    }
    
}

//end class
